﻿using Qy.Common;
using Qy.Models;
using Qy.Service;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace Qy.Web.Authorize
{
    public class LoginUtil
    {
        private readonly UserService _adminUserService;
        private readonly UserGroupService _adminUserGroupService;
        public LoginUtil(UserService adminUserService, UserGroupService adminUserGroupService)
        {
            _adminUserService = adminUserService;
            _adminUserGroupService = adminUserGroupService;
        }

        /// <summary>
        /// 登录用户ID
        /// </summary>
        /// <returns></returns>
        public int LoginUserId()
        {
            return App.HttpContext.GetUId();
        }

        /// <summary>
        /// 登录用户角色ID
        /// </summary>
        /// <returns></returns>
        public int LoginGroupId()
        {
            return App.HttpContext.GetGId();
        }

        public UserAction UserAction()
        {
            var httpContext = App.HttpContext;
            if (httpContext == null)
                return null;

            UserAction userAction = new()
            {
                UserId = httpContext.GetUId(),
                Controller = httpContext.GetController(),
                Action = httpContext.GetAction(),
                Ip = httpContext.GetClientUserIp(),
            };
            return userAction;
        }

        public async Task<UserInfo> UserInfoAsync()
        {
            int userId = LoginUserId();
            if (userId<1)
            {
                return null;
            }
            ViewUser adminUser = await _adminUserService.GetAsync(userId);
            UserGroup adminUserGroup = await _adminUserGroupService.GetAsync(adminUser.Gid);
            
            UserInfo viewUser = new()
            {
                UserId = userId,
                Gid = adminUser.Gid,
                DeptId = adminUser.DeptId,
                PostId = adminUser.PostId,
                PostName = adminUser.PostName,
                PostCode = adminUser.PostCode,
                DeptName = adminUser.DeptName,
                Username = adminUser.Username,
                Nickname = adminUser.Nickname,
                Status = adminUser.Status,
                Avatar = adminUser.Avatar,
                Phone = adminUser.Phone,
                Sex = adminUser.Sex,
                Groupname = adminUserGroup.Groupname,
            };
            try
            {
                viewUser.SystemRole = JsonSerializer.Deserialize<List<string>>(adminUserGroup.Systemrole);
            }
            catch { }
            return viewUser;
        }

    }
}
